import { Descriptions, Form, Input, Table, type TableProps } from 'antd'
import React, { useContext, useEffect, useRef, useState } from 'react'
import type { GetRef, InputRef } from 'antd'
import { Space } from 'antd'
interface DetailConfigProps {
    key: string
    label: string
    children: string
}
interface Item {
    key: string
    name: string
    age: string
    address: string
}
interface DataType {
    key: React.Key
    name: string
    age: string
    address: string
}
interface EditableRowProps {
    index: number
}
interface EditableCellProps {
    title: React.ReactNode
    editable: boolean
    dataIndex: keyof Item
    record: Item
    handleSave: (record: Item) => void
}
type FormInstance<T> = GetRef<typeof Form<T>>
const EditableCell: React.FC<React.PropsWithChildren<EditableCellProps>> = ({
    title,
    editable,
    children,
    dataIndex,
    record,
    handleSave,
    ...restProps
}) => {
    const [editing, setEditing] = useState(false)
    const inputRef = useRef<InputRef>(null)
    const form = useContext(EditableContext)!

    useEffect(() => {
        if (editing) {
            inputRef.current?.focus()
        }
    }, [editing])

    const toggleEdit = () => {
        setEditing(!editing)
        form.setFieldsValue({ [dataIndex]: record[dataIndex] })
    }

    const save = async () => {
        try {
            const values = await form.validateFields()

            toggleEdit()
            handleSave({ ...record, ...values })
        } catch (errInfo) {
            console.log('Save failed:', errInfo)
        }
    }

    let childNode = children

    if (editable) {
        childNode = editing ? (
            <Form.Item
                style={{ margin: 0 }}
                name={dataIndex}
                rules={[{ required: true, message: `${title} is required.` }]}
            >
                <Input ref={inputRef} onPressEnter={save} onBlur={save} />
            </Form.Item>
        ) : (
            <div
                className="editable-cell-value-wrap"
                style={{ paddingInlineEnd: 24 }}
                onClick={toggleEdit}
            >
                {children}
            </div>
        )
    }

    return <td {...restProps}>{childNode}</td>
}

const EditableContext = React.createContext<FormInstance<any> | null>(null)
const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
    const [form] = Form.useForm()
    return (
        <Form form={form} component={false}>
            <EditableContext.Provider value={form}>
                <tr {...props} />
            </EditableContext.Provider>
        </Form>
    )
}
export function DetailConfig({
    detailInfo,
    dialogContent,
}: {
    detailInfo: DetailConfigProps[]
    dialogContent: boolean
}) {
    type ColumnTypes = Exclude<TableProps<DataType>['columns'], undefined>
    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    }
    const [dataSource, setDataSource] = useState<DataType[]>([
        {
            key: '0',
            name: 'Edward King 0',
            age: '32',
            address: 'London, Park Lane no. 0',
        },
        {
            key: '1',
            name: 'Edward King 1',
            age: '32',
            address: 'London, Park Lane no. 1',
        },
    ])

    const defaultColumns: (ColumnTypes[number] & {
        editable?: boolean
        dataIndex: string
    })[] = [
        {
            title: 'name',
            dataIndex: 'name',
            width: '30%',
            editable: true,
        },
        {
            title: 'age',
            dataIndex: 'age',
        },
        {
            title: 'address',
            dataIndex: 'address',
        },
    ]
    const columns = defaultColumns.map((col) => {
        if (!col.editable) {
            return col
        }
        return {
            ...col,
            onCell: (record: DataType) => ({
                record,
                editable: col.editable,
                dataIndex: col.dataIndex,
                title: col.title,
                handleSave,
            }),
        }
    })
    const handleSave = (row: DataType) => {
        const newData = [...dataSource]
        const index = newData.findIndex((item) => row.key === item.key)
        const item = newData[index]
        newData.splice(index, 1, {
            ...item,
            ...row,
        })
        setDataSource(newData)
    }
    useEffect(() => {
        // 可以根据 dialogContent 的变化执行一些操作
    }, [dialogContent])
    return (
        <>
            <Space
                direction="vertical"
                size="middle"
                style={{ display: 'flex' }}
            >
                <Descriptions
                    title="申报概览"
                    bordered
                    size="small"
                    items={detailInfo}
                />
                <Table<DataType>
                    components={components}
                    title={() => '申报明细'}
                    rowClassName={() => 'editable-row'}
                    bordered
                    dataSource={dataSource}
                    columns={columns as ColumnTypes}
                />
            </Space>
        </>
    )
}
